
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
using UwinEducation.Application.Common.Interfaces;

namespace UwinEducation.Application.Services
{
    /// <summary>
    /// Redis缓存服务实现
    /// </summary>
    public class RedisCacheService : ICacheService
    {
        private readonly IDistributedCache _cache;
        private readonly DistributedCacheEntryOptions _defaultOptions;

        public RedisCacheService(IDistributedCache cache)
        {
            _cache = cache;
            _defaultOptions = new DistributedCacheEntryOptions
            {
                //TODO 配置缓存过期时间

                //设置24小时过期
            
                //表示缓存的绝对过期时间，相对于当前时间计算,这是缓存的“硬性”到期时间，过了这个时间，缓存一定会被移除。
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60*24),//24小时
                //表示缓存的滑动过期时间,如果缓存条目在 60 分钟内没有被访问（即没有读取操作），它会过期。
                //设置24小时过期
                SlidingExpiration = TimeSpan.FromMinutes(60*24)
            };
        }

        public async Task<T> GetAsync<T>(string key)
        {
            var value = await _cache.GetStringAsync(key);
            return string.IsNullOrWhiteSpace(value) ? default(T) : JsonSerializer.Deserialize<T>(value);
        }

        public async Task SetAsync<T>(string key, T value, TimeSpan? expiration = null)
        {
            var options = expiration.HasValue
                ? new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = expiration }
                : _defaultOptions;

            var serializedValue = JsonSerializer.Serialize(value);
            await _cache.SetStringAsync(key, serializedValue, options);
        }

        public async Task RemoveAsync(string key)
        {
            await _cache.RemoveAsync(key);
        }
    }
}